<script setup lang="ts">
import { reactive, computed, ref, toRefs, onMounted, watch } from "vue";
import { ContentWrap } from "@/components/ContentWrap";
import { ElInput, ElMessage } from "element-plus";
import type { ElForm } from "element-plus";
import { Edit, Plus, Minus } from "@element-plus/icons-vue";
import { BaseButton } from "@/components/Button";
import { useRouter, useRoute } from "vue-router";
import {
  droneAdd,
  droneEdit,
  droneDetail,
  mountEquipmentList,
} from "@/api/resource-manage";
import {
  baseOpions,
  mountForm,
  setpOpions,
  getType,
  getMountType,
  getSeriesType,
  mountGroup,
  mountGroupValue
} from "./config/info";
import { dataToSelect } from "@/utils";

// 路由
const router = useRouter();
const { query } = useRoute();

// 基础信息ref
const elFormRef = ref<ComponentRef<typeof ElForm>>();
const formSize = ref("default");

// add 新增  eidt 编辑   detail 详情
let infoType = computed(() => {
  return query?.type ?? "add";
});

// 基础信息
const formObj = computed(() => {
  return {
    ...baseOpions,
  };
});

// 表单参数
const modalForm = computed(() => {
  if (infoType.value !== "add") {
    return reactive({
      code: apiObj.value.code, // 无人机实名状态(1已实名 0未实名)
      authenticationStatus: apiObj.value.authenticationStatus, // 无人机实名状态(1已实名 0未实名)
      brand: apiObj.value.brand, // 无人机品牌
      modelCode: apiObj.value.modelCode, // 无人机型号
      status: apiObj.value.status, // 可用状态
      name: apiObj.value.name, // 无人机名称
      coverage: apiObj.value.coverage, // 覆盖范围
      id: apiObj.value.id,
    });
  } else {
    return reactive({
      ...formObj.value.modalForm,
    });
  }
});



// 关联挂载设备
const mountFormObj = computed(() => {
  return {
    ...mountForm,
  };
});

// 关联挂载设备 表单参数
const mountModalForm = computed(() => {
  if (infoType.value !== "add") {
    const mounts = apiObj.value.mounts?.map((item) => {
      return {
        code: item.code, // 挂载编号
        type: item.type, // 挂载类型
        brand: item.brand, // 挂载品牌 drone_DJ 大疆  drone_TH 拓恒
        series: item.series, // 挂载系列
        mountTypeArr:mountGroupValue.mountTypeArr,
        mountBrandArr:mountGroupValue.mountBrandArr,
        seriesTypeArr:[],
        codeArr:[],
      };
    }) || [{
      code: null, // 挂载编号
      type:null, // 挂载类型
      brand:null, // 挂载品牌 drone_DJ 大疆  drone_TH 拓恒
      series:null, // 挂载系列 
    }];
    return reactive(mounts)
  } else {
    return reactive([{
      code: null, // 挂载编号
      type:null, // 挂载类型
      brand:null, // 挂载品牌 drone_DJ 大疆  drone_TH 拓恒
      series:null, // 挂载系列 
      mountTypeArr:mountGroupValue.mountTypeArr,
      mountBrandArr:mountGroupValue.mountBrandArr,
      seriesTypeArr:[],
      codeArr:[],
    }]);
  }
});

// 挂载型号
const changeAttr = async function (key, value,options, index) {
  // console.log(key, value, index);
  // 切换品牌更新挂载型号
  if (key === "brand" && value) {
    mountModalForm.value[index]['seriesTypeArr'] = await getSeriesType(value);
  } else if (key === "brand" && !value) {
    mountFormObj.value[index][options]  = [];
    mountModalForm.value[index].series = null;
  }

  const type = mountModalForm.value[index].type;
  const brand = mountModalForm.value[index].brand;
  const series = mountModalForm.value[index].series;
  console.log('type, brand, series ',type, brand, series )
  if (type && brand && series) {
    const { data } = await mountEquipmentList({ type, brand, series });
    mountModalForm.value[index]['codeArr'] = dataToSelect(data, {
      label: "code",
      value: "id",
    });
  }
};


// 操作记录
const setpsShow = ref(true);
// 云台参数
const setpActive = ref(0);

// 操作记录
const setps = computed(() => {
  return {
    ...setpOpions,
  };
});

// 确认
const submit = async (formEl) => {
  if (!formEl) return;
  const valid = await formEl.validate();
  if (!!valid) {
    let query = {
      ...modalForm.value,
      mountIds:
        mountModalForm.value.map((item) => {
          return item.code;
        }) || [],
    };
    //新增
    if (infoType.value === "add") {
      const { msg } = (await droneAdd(query)) as any;
      ElMessage.success(msg);
    } else {
      // 编辑
      const { msg } = (await droneEdit(query)) as any;
      ElMessage.success(msg);
    }
    returnLinK();
  } else {
    console.log("error submit!");
  }
};

// 返回
const returnLinK = () => {
  router.go(-1);
};

// 关联挂载设备
const mountRef = ref<ComponentRef<typeof ElForm>>();

// 载入
onMounted(() => {
  init();
});

// 载入
const init = () => {
  getType();
  getMountType();
  if (infoType.value !== "add") {
    getDeail(query?.id);
  }
};

// 接口数据详情
let apiObj = ref<T>({});
// 获取详情
const getDeail = async function (droneId) {
  const { data } = (await droneDetail({ droneId })) as any;
  apiObj.value = { ...data };
};


const  addGroup  = ()=>{
  mountModalForm.value.push({
      code: null, // 挂载编号
      type:null, // 挂载类型
      brand:null, // 挂载品牌 drone_DJ 大疆  drone_TH 拓恒
      series:null, // 挂载系列 
      mountTypeArr:mountGroupValue.mountTypeArr,
      mountBrandArr:mountGroupValue.mountBrandArr,
      seriesTypeArr:[],
      codeArr:[],
    }
  )
}
const  removeGroup  = (index)=>{
  mountModalForm.value.splice(index,1)
}

</script>

<template>
  <!--  基础信息 -->
  <ContentWrap :title="`基础信息`" style="margin-bottom: 20px">
    <el-form
      ref="elFormRef"
      :model="modalForm"
      :rules="formObj.modalRules"
      label-width="120px"
      :size="formSize"
      status-icon
      :disabled="infoType === 'detail'"
    >
      <el-row :gutter="10">
        <el-col
          v-for="(formItem, index) in formObj.formItem"
          :key="index"
          v-bind="formItem.row"
          :class="formItem.key === 'code' && 'alone_row'"
        >
          <el-form-item
            v-if="formItem.key === 'code'"
            :label="formItem.label"
            :prop="formItem.key"
            style="width: 33.33%"
          >
            <el-input
              v-if="formItem.type === 'input'"
              v-model="modalForm[formItem.key]"
              v-bind="formItem.props"
            />
          </el-form-item>
          <el-button
            v-if="formItem.key === 'code'"
            :style="{ marginLeft: '15px' }"
            type="primary"
            >获取认证信息</el-button
          >
          <el-form-item v-else :label="formItem.label" :prop="formItem.key">
            <el-input
              v-if="formItem.type === 'input'"
              v-model="modalForm[formItem.key]"
              v-bind="formItem.props"
            >
              <template v-if="formItem.key === 'coverage'" #append>km</template>
            </el-input>
            <el-select
              v-if="formItem.type === 'select'"
              v-model="modalForm[formItem.key]"
              v-bind="formItem.props"
            >
              <el-option
                v-for="item in formItem.options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </ContentWrap>
  <!-- 管理挂载设备 -->
  <ContentWrap :title="`关联挂载设备`" style="margin-bottom: 20px">
    <el-form
      ref="mountRef"
      :model="mountFormObj.modalForm"
      label-width="120px"
      :size="formSize"
      status-icon
      :disabled="infoType === 'detail'"
    >
      <div class="mount-group" v-for="(group, gi) in mountModalForm" :key="gi">
        <div class="group">
          <el-row
            :gutter="10"
            v-for="(formItem, index) in mountFormObj.mounts"
            :key="index"
          >
            <el-col v-bind="child.row" v-for="(child, chi) in formItem" :key="chi">
              <el-form-item :label="child.label" :prop="child.key">
                <el-select
                  v-model="group[child.key]"
                  v-bind="child.props"
                  @change="() => changeAttr(child.key, group[child.key],child.options, gi)"
                >
                  <el-option
                    v-for="item in group[child.options]"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div class="handle-warp">
          <el-button type="primary" v-if="!gi" :icon="Plus"  @click="addGroup()"/>
          <el-button type="danger" v-else :icon="Minus" @click="removeGroup(gi)"/>
        </div>
      </div>
    </el-form>
  </ContentWrap>
  <!-- 操作记录 -->
  <ContentWrap :title="`操作记录`" style="margin-bottom: 20px" >
    <el-steps :active="setpActive"  align-center>
      <el-step
        v-for="(item, index) in setps"
        :key="index"
        :title="item.title"
        :description="item.description"
      >
        <template #icon>
          <span :class="item.icon" class="icon_span"></span>
        </template>
      </el-step>
    </el-steps>
  </ContentWrap>
  <el-row>
    <el-col :span="24">
      <BaseButton @click="returnLinK()">返回</BaseButton>
      <BaseButton v-if="infoType !== 'detail'" type="primary" @click="submit(elFormRef)"
        >确认</BaseButton
      >
    </el-col>
  </el-row>
</template>

<style lang="less" scoped>
.el-form-item__content {
  > div {
    width: 100%;
  }
}

.alone_row {
  display: flex;
  margin-right: 25px;
}

.mount-group {
  display: flex;
  .group {
    flex: 1;
  }
  .handle-warp {
    width: 110px;
    margin-left: 15px;
  }
}
</style>
